package com.jyy.prefabricated.service;

import com.jyy.prefabricated.entity.ExamPaperArea;
import com.jyy.prefabricated.entity.ExamPaperAreaRule;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.ExamPaperAreaMapper;
import com.jyy.prefabricated.mapper.ExamPaperAreaRuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class ExamPaperAreaService {

    @Autowired
    private ExamPaperAreaMapper areaMapper;

    @Autowired
    private ExamPaperAreaRuleMapper ruleMapper;


    /**
     * 新增
     * @param area
     * @return
     */
    public int insert(ExamPaperArea area){
        areaMapper.insert(area);
        saveAreaId2Rule(area.getRules(), area.getId());
        return area.getId();
    }

    /**
     * 将区域id写入规则列表
     * @param rules
     * @param id
     */
    public void saveAreaId2Rule(List<ExamPaperAreaRule> rules, Integer id){
        if(rules.size() > 0){
            for(ExamPaperAreaRule rule : rules){
                rule.setAreaId(id);
            }
            ruleMapper.updateBatch(rules);
        }
    }
    /**
     * 将区域id写入规则列表
     * @param rules
     * @param id
     */
    public void addAreaId2Rule(List<ExamPaperAreaRule> rules, Integer id){
        if(rules.size() > 0){
            for(ExamPaperAreaRule rule : rules) {
                rule.setId(null);
                rule.setAreaId(id);
                ruleMapper.insert(rule);
            }
        }
    }

    /**
     * 更新
     * @param area
     * @return
     */
    public int update(ExamPaperArea area){
        if(area.getId() == null){
            throw new CustomException("参数id不能为空");
        }
        saveAreaId2Rule(area.getRules(), area.getId());
        return areaMapper.updateByPrimaryKeySelective(area);
    }
    /**
     * 添加规则
     * @param area
     * @return
     */
    public int add(ExamPaperArea area){
        area.setId(null);
        areaMapper.insert(area);
        addAreaId2Rule(area.getRules(), area.getId());
        return  0;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public int delete(Integer id){
        ruleMapper.deleteByAreaId(id);
        return areaMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public ExamPaperArea selectById(Integer id){
        return areaMapper.selectByPrimaryKey(id);
    }
}
